# -*- coding: utf-8 -*-良
#   edit brow界面通用管理模块
# @Time    ： 2024/4/7  12:08
# @Auther  ： 徐良
# File     :  baseEBworkPanel.py

from PySide6.QtCore import Qt
from baseClass.baseQWidget import BaseQWidget
from baseUI.treeHeadGridUI import Ui_Form
from share.dataFactory import SqlForSave
from share.makeTree import MakeTree
from utils.ebWork import EBWork
import share.globalvar as gol
from mesParts.delegate.delegates import DelegateCheckColorNotEdit
from share.bioDialog import Infomation
from PySide6.QtWidgets import QMessageBox, QDataWidgetMapper

class BaseEBworkPanel(BaseQWidget, EBWork, Ui_Form):
    """
    pass
    """
    def __init__(self, msDict, parent=None):
        super(BaseEBworkPanel, self).__init__()
        self.queryPanel = None
        self.setAttribute(Qt.WA_StyledBackground)
        self.setupUi(self)
        self.toolbarFlag = 'browse'
        self.stackedW = "Yes"

        self.mapper = QDataWidgetMapper()

        self.baseDbType = gol.getValue('baseDbType')
        msDict = eval(msDict)
        print(msDict)
        self.doInitWork(msDict)
        self.initPara()
        self.auditAfter.connect(self.onAuditAfter)

        self.setLabel()
        self.buildTree()
        self.readData(self.FMainSql)
        self.setEditPanel()

        self.treeWidget.itemDoubleClicked.connect(self.onTreeItemDBClick)
        self.saveActionSignal.connect(self.setToolbarSaveButton)
        self.tableView.clicked.connect(self.onTableViewClicked)
        self.checkBox.clicked.connect(self.onCheckBoxClicked)

        self.toolbarFinish = 0    # 工具栏设置完成状态，0 未完成，1，完成，由主控模块设置
        self.toolbarStateTimer.timeout.connect(self.check_toolbarFinish)
        self.toolbarStateTimer.start(500)


    def getMoveButton(self):
        """
        获取四个命令按钮，首记录，下一条，上一条，尾记录
        :return:
        """
        self.firstBtn = self.getButton('首记录')
        self.nextBtn = self.getButton('下一条')
        self.previousBtn = self.getButton('上一条')
        self.lastBtn = self.getButton('尾记录')

    def buildTree(self):
        """

        :return:
        """
        makeTree = MakeTree(self.FTreeSql, self.treeWidget, self.baseDbType)
        makeTree.createTree()
        self.treeWidget.setColumnWidth(0, 150)

    def readData(self, sql):
        """
        读取数据
        :return:
        """
        self.mainModel = self.getMainModel(sql)
        self.tableView.setModel(self.mainModel)


        self.tableView.setColumnWidthForList(self.browse_FColumnWidthList)
        self.tableView.setHideColumnForCol(self.browse_FVisibleList)

        # 代理
        pdict = {'model': self.mainModel, 'color': 1, 'selOption': 0,
                 'widgetList': self.getA3_FWidgetList()}
        delegateDict = self.getBorwseDelegateDic()
        delegateDict.update(pdict)
        delete = DelegateCheckColorNotEdit(delegateDict)
        self.tableView.setItemDelegate(delete)

        if self.mainModel.rowCount() > 0:
            index = self.mainModel.index(0, 0)
            self.tableView.setCurrentIndex(index)

        self.mainModel.dataChangedSignal.connect(self.onModelDataChanged)

    def setLabel(self):

        self.lbl_editTitle.setText(self.FEditTitle)
        self.lbl_browseTitle.setText(self.FBrowseTitle)

    def actionSelect(self, q):
        sel = q.text()
        if sel == '首记录':
            self.toFirst()
        elif sel == '上一条':
            self.toPrevious()
        elif sel == '下一条':
            self.toNext()
        elif sel == '尾记录':
            self.toLast()
        elif sel == '增加':
            count = self.mainModel.rowCount()
            self.mainModel.insertRows(count)
            index = self.mainModel.index(count, 0)
            self.onTableViewClicked(index)
        elif sel == '插入':
            index = self.tableView.currentIndex()
            row = index.row()
            self.mainModel.insertRows(row)
            self.onTableViewClicked(index)
        elif sel == '删除':
            index = self.tableView.currentIndex()
            row = index.row()
            self.mainModel.removeRows(row)
            index = self.tableView.currentIndex()
            if index.isValid():
                self.onTableViewClicked(index)
        elif sel == '审核':
            self.audit(1)
        elif sel == '反审核':
            self.audit(0)
        elif sel == '刷新':
            self.readData(self.FMainSql)
        elif sel == '导出':
            print('导出')

    def audit(self, iFlag):
        """
        审核
        :return:
        """
        # 判断是否需要先保存
        if self.checkSave():
            ok = Infomation.question('数据已更改，是否需要保存？')
            if ok == QMessageBox.Yes:
                return

        index = self.tableView.currentIndex()

        if not index.isValid():
            Infomation.info('请选定记录')
            return

        row = index.row()
        sfid = self.mainModel.record(0).value('FId')

        if iFlag:
            sVal = 'admin'
        else:
            sVal = ''
        # 保存到数据库
        sql = "update {tableName} set FChecker='{val}' where Fid={fid}"
        sql = sql.format(tableName=self.getA1_FTableName(), val=sVal, fid=str(sfid))
        ok = SqlForSave.execSqlList([sql], self.baseDbType)
        if ok['ret']:

            icol = self.getBrowseColumn('FChecker')
            icol2 = self.getBrowseColumn('FState')
            if iFlag:
                idx = self.mainModel.index(row, icol)
                self.mainModel.setData(idx, 'admin')

                idx = self.mainModel.index(row, icol2)
                self.mainModel.setData(idx, '已审核')
            else:
                idx = self.mainModel.index(row, icol)
                self.mainModel.setData(idx, '')
                idx = self.mainModel.index(row, icol2)
                self.mainModel.setData(idx, '未审核')

            self.auditAfter.emit({'row': row, 'iFlag': iFlag})

    def checkSave(self):
        btn = self.getButton('保存')
        return btn.isEnabled()

    def save(self):
        """
        保存单据
        """
        self.tableSave()

    def toNext(self):
        """
        处理下一条
        :return:
        """
        index = self.tableView.currentIndex()
        if index.isValid():
            row = index.row()
            if row < self.mainModel.rowCount():
                self.setBrowsePanel(row + 1)
                self.mapper.toNext()
            self.onRecordChanged(row + 1)
        else:
            return

    def toPrevious(self):
        """
        上一条
        :return:
        """
        index = self.tableView.currentIndex()
        if index.isValid():
            row = index.row()
            if row < self.mainModel.rowCount():
                self.setBrowsePanel(row - 1)
                self.mapper.toPrevious()
            self.onRecordChanged(row - 1)
        else:
            return

    def toLast(self):
        """
        最后一条
        :return:
        """
        if self.mainModel.rowCount() > 0:
            row = self.mainModel.rowCount() - 1
            self.setBrowsePanel(row)
            self.mapper.toLast()
            self.onRecordChanged(row)
        else:
            return

    def toFirst(self):
        """
        第一条
        :return:
        """
        if self.mainModel.rowCount() > 0:
            self.setBrowsePanel(0)
            self.mapper.toFirst()
            self.onRecordChanged(0)
        else:
            return

    def onRecordChanged(self, row):
        """属性表记录移动"""
        self.getMoveButton()

        if row == -1:
            return
        # 处理仅有一条纪录
        if row == 1:
            self.firstBtn.setEnabled(False)
            self.previousBtn.setEnabled(False)
            self.nextBtn.setEnabled(False)
            self.lastBtn.setEnabled(False)

        first = (row == 0)  # 是否首记录
        last = (row == self.mainModel.rowCount() - 1)  # 是否尾记录
        self.firstBtn.setEnabled(not first)
        self.previousBtn.setEnabled(not first)
        self.nextBtn.setEnabled(not last)
        self.lastBtn.setEnabled(not last)

        self.setToolbarButtons()

    def onTableViewClicked(self, index):
        if index.isValid():
            row = index.row()
            self.setBrowsePanel(row)
            self.mapper.setCurrentIndex(row)
            self.onRecordChanged(row)
            self.setToolbarButtons()

    def onCheckBoxClicked(self):
        """
        响应checkBox点击事件
        :return:
        """
        if self.checkBox.isChecked():
            self.setModelFSel(1)
        else:
            self.setModelFSel(0)


if __name__ == '__main__':
    import sys
    from PySide6.QtWidgets import QApplication, QDataWidgetMapper

    app = QApplication(sys.argv)
    dic = "{'msFNumber': '04.01', 'msClass': '10', 'msSaveType':1}"
    window = BaseEBworkPanel(dic)
    window.show()
    sys.exit(app.exec())

